/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 音乐搜索页面 - 使用MVVM架构和Provider状态管理
 * 迁移自原始项目的 MusicSearchV，保持完全相同的UI设计和用户体验
 */

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../viewmodels/music_search_view_model.dart';
import '../viewmodels/music_player_view_model.dart';
import '../models/page_state.dart';
import '../models/music_item_model.dart';
import '../widgets/common/search_history_widget.dart';
import '../widgets/music_widgets/music_search_item_widget.dart';
import '../widgets/common/loading_widget.dart';
import '../widgets/common/empty_state_widget.dart';
import '../widgets/common/error_state_widget.dart';
import '../services/floating_player_service.dart';
import '../utils/error_handler.dart';

/// 音乐搜索页面
/// 提供音乐搜索、搜索历史管理、搜索结果展示等功能
/// 完全迁移自原始项目，保持UI和交互逻辑完全一致
class MusicSearchPage extends StatefulWidget {
  const MusicSearchPage({super.key});

  @override
  State<MusicSearchPage> createState() => _MusicSearchPageState();
}

class _MusicSearchPageState extends State<MusicSearchPage>
    with FloatingPlayerPageMixin {
  late TextEditingController _textEditingController;
  late ScrollController _scrollController;
  late FocusNode _searchFocusNode;

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController();
    _scrollController = ScrollController();
    _searchFocusNode = FocusNode();

    // 添加滚动监听器，实现自动加载更多
    _scrollController.addListener(_onScroll);

    // 初始化搜索ViewModel
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        Provider.of<MusicSearchViewModel>(context, listen: false).init();
        initFloatingPlayer();
      }
    });
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    _scrollController.dispose();
    _searchFocusNode.dispose();
    disposeFloatingPlayer();
    super.dispose();
  }

  /// 滚动监听器 - 实现自动加载更多
  void _onScroll() {
    if (!mounted) return;
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent * 0.8) {
      // 滚动到80%时触发加载更多
      final viewModel =
          Provider.of<MusicSearchViewModel>(context, listen: false);
      if (viewModel.canLoadMore) {
        viewModel.loadMore();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: _buildAppBar(),
      body: SafeArea(
        child: Consumer<MusicSearchViewModel>(
          builder: (context, viewModel, child) {
            return _buildBody(viewModel);
          },
        ),
      ),
    );
  }

  /// 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back, color: Colors.black87),
        onPressed: () => Navigator.of(context).pop(),
      ),
      title: _buildSearchBar(),
      titleSpacing: 0,
    );
  }

  /// 构建搜索栏
  Widget _buildSearchBar() {
    return Container(
      height: 36,
      margin: const EdgeInsets.only(right: 16),
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(18),
      ),
      child: Row(
        children: [
          const SizedBox(width: 12),
          const Icon(
            Icons.search,
            color: Colors.grey,
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: TextField(
              controller: _textEditingController,
              focusNode: _searchFocusNode,
              decoration: const InputDecoration(
                hintText: '搜索音乐、歌手、专辑',
                hintStyle: TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(vertical: 8),
              ),
              style: const TextStyle(
                fontSize: 14,
                color: Colors.black87,
              ),
              textInputAction: TextInputAction.search,
              onSubmitted: _onSearchSubmitted,
            ),
          ),
          Consumer<MusicSearchViewModel>(
            builder: (context, viewModel, child) {
              if (_textEditingController.text.isNotEmpty ||
                  viewModel.currentQuery.isNotEmpty) {
                return IconButton(
                  icon: const Icon(
                    Icons.clear,
                    color: Colors.grey,
                    size: 18,
                  ),
                  onPressed: _onClearSearch,
                );
              }
              return const SizedBox(width: 12);
            },
          ),
        ],
      ),
    );
  }

  /// 构建页面主体
  Widget _buildBody(MusicSearchViewModel viewModel) {
    // 根据页面状态显示不同内容
    switch (viewModel.state) {
      case PageState.loading:
        if (viewModel.searchList.isEmpty) {
          // 首次加载显示全屏加载
          return const LoadingWidget(message: '搜索中...');
        } else {
          // 加载更多时显示列表+底部加载指示器
          return _buildSearchResults(viewModel, showLoadingMore: true);
        }

      case PageState.success:
      case PageState.noMore:
        return _buildSearchResults(viewModel);

      case PageState.empty:
        if (viewModel.currentQuery.isEmpty) {
          // 没有搜索关键词时显示搜索历史
          return _buildSearchHistory(viewModel);
        } else {
          // 搜索无结果
          return EmptyStateWidget(
            message: '未找到相关音乐',
            icon: Icons.search_off,
            onRetry: () => _retrySearch(viewModel),
          );
        }

      case PageState.error:
        return ErrorStateWidget(
          message: viewModel.errorMessage ?? '搜索失败，请重试',
          onRetry: () => _retrySearch(viewModel),
        );

      case PageState.idle:
      default:
        return _buildSearchHistory(viewModel);
    }
  }

  /// 构建搜索历史和热门搜索
  Widget _buildSearchHistory(MusicSearchViewModel viewModel) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: SearchHistoryWidget(
        historyItems: viewModel.historyItems,
        hotItems: viewModel.hotItems,
        onItemTap: _onHistoryItemTap,
        onClearHistory: () => _onClearHistory(viewModel),
        historyTitle: '历史搜索',
        hotTitle: '热门搜索',
        showHistory: viewModel.historyItems.isNotEmpty,
        showHot: viewModel.hotItems.isNotEmpty,
      ),
    );
  }

  /// 构建搜索结果列表
  Widget _buildSearchResults(
    MusicSearchViewModel viewModel, {
    bool showLoadingMore = false,
  }) {
    return RefreshIndicator(
      onRefresh: () => _onRefresh(viewModel),
      child: ListView.builder(
        controller: _scrollController,
        padding: const EdgeInsets.symmetric(vertical: 20),
        itemCount: viewModel.searchList.length + (showLoadingMore ? 1 : 0),
        itemBuilder: (context, index) {
          // 显示加载更多指示器
          if (index == viewModel.searchList.length) {
            return _buildLoadingMoreIndicator(viewModel);
          }

          // 显示搜索结果项
          final musicItem = viewModel.searchList[index];
          return _buildSearchResultItem(musicItem, index, viewModel);
        },
      ),
    );
  }

  /// 构建搜索结果项
  Widget _buildSearchResultItem(
    MusicItemModel musicItem,
    int index,
    MusicSearchViewModel viewModel,
  ) {
    return InkWell(
      onTap: () => _onSearchItemTap(musicItem, index, viewModel),
      child: MusicSearchItemWidget(
        musicItem: musicItem,
        query: viewModel.currentQuery,
        onTap: () => _onSearchItemTap(musicItem, index, viewModel),
      ),
    );
  }

  /// 构建加载更多指示器
  Widget _buildLoadingMoreIndicator(MusicSearchViewModel viewModel) {
    if (viewModel.state == PageState.noMore) {
      return const Padding(
        padding: EdgeInsets.all(16),
        child: Center(
          child: Text(
            '没有更多结果了',
            style: TextStyle(
              color: Colors.grey,
              fontSize: 14,
            ),
          ),
        ),
      );
    }

    return const Padding(
      padding: EdgeInsets.all(16),
      child: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              width: 16,
              height: 16,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
            SizedBox(width: 8),
            Text(
              '加载更多...',
              style: TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 搜索提交处理
  void _onSearchSubmitted(String query) {
    if (query.trim().isEmpty) {
      _showMessage('请输入搜索内容');
      return;
    }

    _hideKeyboard();
    if (!mounted) return;
    final viewModel = Provider.of<MusicSearchViewModel>(context, listen: false);
    viewModel.search(query: query.trim());
  }

  /// 清空搜索处理
  void _onClearSearch() {
    _textEditingController.clear();
    if (!mounted) return;
    final viewModel = Provider.of<MusicSearchViewModel>(context, listen: false);
    viewModel.clearSearchResults();
    _searchFocusNode.requestFocus();
  }

  /// 历史搜索项点击处理
  void _onHistoryItemTap(SearchItem item) {
    _textEditingController.text = item.text;
    _onSearchSubmitted(item.text);
  }

  /// 清空搜索历史处理
  void _onClearHistory(MusicSearchViewModel viewModel) {
    viewModel.clearSearchHistory();
  }

  /// 搜索结果项点击处理
  void _onSearchItemTap(
    MusicItemModel musicItem,
    int index,
    MusicSearchViewModel viewModel,
  ) async {
    if (musicItem.disabled) {
      _showMessage('平台版权原因无法播放，请尝试其它平台');
      return;
    }

    try {
      // 找到在可播放列表中的索引
      int playableIndex = 0;
      for (int i = 0; i < viewModel.searchCanPlayList.length; i++) {
        if (viewModel.searchCanPlayList[i].id == musicItem.id) {
          playableIndex = i;
          break;
        }
      }

      // 设置播放列表并开始播放
      if (!mounted) return;
      final playerViewModel =
          Provider.of<MusicPlayerViewModel>(context, listen: false);
      playerViewModel.setPlaylist(
        viewModel.searchCanPlayList,
        startIndex: playableIndex,
      );

      // 开始播放
      if (viewModel.searchCanPlayList.isNotEmpty && playableIndex >= 0) {
        await playerViewModel.playAtIndex(playableIndex);
      }
      if (!mounted) return;

      // 导航到播放页面
      Navigator.of(context).pushNamed(
        '/music_player',
        arguments: {
          'keyword': viewModel.currentQuery,
          'page': viewModel.currentPage,
        },
      );
    } catch (error, stackTrace) {
      ErrorHandler.handleError(error, stackTrace);
      if (mounted) {
        _showMessage('播放失败，请重试');
      }
    }
  }

  /// 下拉刷新处理
  Future<void> _onRefresh(MusicSearchViewModel viewModel) async {
    if (viewModel.currentQuery.isNotEmpty) {
      await viewModel.refresh();
    }
  }

  /// 重试搜索
  void _retrySearch(MusicSearchViewModel viewModel) {
    if (viewModel.currentQuery.isNotEmpty) {
      viewModel.search(query: viewModel.currentQuery);
    } else if (_textEditingController.text.isNotEmpty) {
      _onSearchSubmitted(_textEditingController.text);
    }
  }

  /// 隐藏键盘
  void _hideKeyboard() {
    FocusScope.of(context).unfocus();
  }

  /// 显示消息提示
  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
        behavior: SnackBarBehavior.floating,
      ),
    );
  }
}
